<script setup>
import {ref, onMounted, reactive,defineProps,watchEffect} from 'vue'
import io from 'socket.io-client';
/***********************************************************
 *  
 *  原则，尽量用数据替代H5的dom操作。可以简化很多原来的墨迹的H5代码。
 * 
 ************************************************************/
 const props = defineProps(['socket','toggleBoard'])

var mycanvas = reactive(null);
var selColor =ref("#404040");
var socket = reactive(null);
var cursorSize = ref(20); // 橡皮擦大小
var Drew = false;
onMounted(()=>{
  
    //  socket = io("localhost:3000");
      socket = props.socket;
      console.log("props.socket=",socket);
    
      socket.on('connect', function() {
        console.log('Connected to server');
        
      });

      socket.on('drawData', function(data) {
            /* Add data to canvas */
            drawRecv(data); 
      });

      socket.on('eraseData', function(data) {
            /* Erase data from canvas */
            eraseData(data); 
      });

      socket.on('clearallData', function() {
            /* Erase data from canvas */
            clearallData(); 
      });

      /**
       * 前端关闭浏览器时，清除session
       */
      socket.on("disconnect", () => {
        // 删除存储在sessionStorage中的数据
        sessionStorage.removeItem("username");
        sessionStorage.removeItem("userList");

        // 清空sessionStorage中的所有数据
        //sessionStorage.clear();
        console.log("Disconnected from server");
      });
})


var colors = reactive(['#404040',
      '#ac4142',
      '#d28445',
      '#f4bf75',
      '#90a959',
      '#6a9fb5'])

const colorClick = function(e){
    disableErase();
    var clicked = document.querySelector('.clicked');
            if(clicked) {
                clicked.classList.remove('clicked');
            }
   if(eraseRef.value.classList.contains("beSelected")==true){
      eraseRef.value.classList.remove('beSelected');
   }
    e.target.classList.add('clicked');
    selColor.value = e.target.style.backgroundColor;
   
}


var isErasing = ref(false);
var eraseRef = ref(null); // 橡皮擦div
const enableErase = function(e){

    var clicked = document.querySelector('.clicked');
     if(clicked) {
        clicked.classList.remove('clicked');
    }
   if(eraseRef.value.classList.contains("beSelected")==false){
      
      eraseRef.value.classList.add('beSelected');
   }

   
    isErasing.value = true;
}
const disableErase = function(){
    isErasing.value = false;
}

/**
 * 垃圾桶-自己处理
 */
const clearAll = function(){
  var ctx=mycanvas.getContext("2d");
  ctx.clearRect(0, 0, mycanvas.width, mycanvas.height);
  /** Send clearall package to Server */
  cleareAllEmit();
}
/**
 * 垃圾桶-发送
 */
const cleareAllEmit = function() {
  socket.emit("clearall");
}
/**
 * 垃圾桶-响应服务器
 */
const clearallData = function(){
  var ctx=mycanvas.getContext("2d");
  ctx.clearRect(0, 0, mycanvas.width, mycanvas.height);
}

/**
 * 橡皮擦擦除-自己处理
 * @param {*} x 
 * @param {*} y 
 * @param {*} ctx 
 */
function erase(x,y,brushSize,ctx){


    // var ctx=mycanvas.getContext("2d");
    ctx.clearRect(x - brushSize, y - brushSize, brushSize * 2, brushSize * 2);

    /** Send erase package to Server. */
    eraseEmit(x,y,brushSize);
    
}
/**
 * 橡皮擦擦除-发送事件
 * @param {*} x 
 * @param {*} y 
 */
function eraseEmit(x,y,brushSize){
  console.log("eraseEmit event=erase");
   socket.emit("erase",{x,y,brushSize})
}
/**
 * 橡皮擦- 响应服务器的广播
 * @param {x,y} data 
 */
function eraseData(data){
    var ctx=mycanvas.getContext("2d");
    ctx.clearRect(data.x - data.brushSize, data.y - data.brushSize, data.brushSize * 2, data.brushSize * 2);
}


/**
 * 基本utils。画线
 */
function draw(x2, y2, x1, y1, ctx, color,brushSize) {
    ctx.strokeStyle = color;
    ctx.lineJoin = 'round';
    ctx.lineWidth = brushSize;
    ctx.beginPath();
    ctx.moveTo(x1, y1);
    ctx.lineTo(x2, y2);
    ctx.closePath();
    ctx.stroke();
    Drew = true;
}
/**
 * 基本utils。画线的事件发送
 */
function drawEmit(x2, y2, x1, y1, color,brushSize) {
    /* Send draw event to server */
    var data = {
        x1: x1,
        y1: y1,
        x2: x2,
        y2: y2,
        clr: color,
        brushSize:brushSize
    };
    console.log('drawEmit event=draw');
    socket.emit('draw', data);
}
/**
 * 基本utils。画方
 * @param {} data 
 */
function drawRecv(data) {
    console.log('Data received', data);
    var ctx=mycanvas.getContext("2d");
    draw(data.x2, data.y2, data.x1, data.y1, ctx, data.clr,data.brushSize);
}

/**
 * 画布的mouseDown事件
 */
var dragging = reactive(false);
var prevX = reactive(0);
var prevY = reactive(0);
function mouseDown(e){
    
        var ctx=mycanvas.getContext("2d");
      
        dragging = true;
       
        if(isErasing.value == false){
            
            var clickX = e.pageX - mycanvas.offsetLeft;
            var clickY = e.pageY - mycanvas.offsetTop;
            
            /* Draw to canvas */
            draw(clickX, clickY, clickX, clickY, ctx, selColor.value,cursorSize.value);
            /* Send draw data to socket */
            drawEmit(clickX, clickY, clickX, clickY, selColor.value,cursorSize.value);
        }else{
            // erasing
            const rect = mycanvas.getBoundingClientRect();
            const x = e.clientX - rect.left;
            const y = e.clientY - rect.top;
            erase(x,y,cursorSize.value,ctx);
            /* TODO Send erase to socket */
        }
       
        
        /* Record our last position */
        prevX = clickX;
        prevY = clickY;
}
/**
 * 画布的mouseMove事件
 */
function mouseMove(e){
  var ctx=mycanvas.getContext("2d");
  // console.log("ctx",ctx);

        if(dragging) {

            if(isErasing.value){
              // erasing
              //console.log("canvas = ",mycanvas);
              const rect = mycanvas.getBoundingClientRect();
              const x = e.clientX - rect.left;
              const y = e.clientY - rect.top;
              erase(x,y,cursorSize.value,ctx);
            }else{
                var clickX = e.pageX - mycanvas.offsetLeft;
                var clickY = e.pageY - mycanvas.offsetTop;
               // console.log("selColor.value="+  selColor.value);
                draw(clickX, clickY, prevX, prevY, ctx, selColor.value,cursorSize.value);
                drawEmit(clickX, clickY, prevX, prevY, selColor.value,cursorSize.value);
                prevX = clickX;
                prevY = clickY;
              }
        }

        
}
/**
 * 画布的mouseUp事件
 */
function mouseUp(e){
  dragging = false;
}

/**
 * 处理笔刷
 */

var brushSizeOpen = ref(false) 
var brush_sizes = ref(null); // dom

var brushToolRef = ref(null);
var popupTop = ref(0);
var popupLeft = ref(0);
function toggleBrush(){

  if (!brushToolRef.value){ return;
  }else{
    const rect = brushToolRef.value.getBoundingClientRect();
    console.log("rect",rect);
    popupTop.value = rect.bottom;
    popupLeft.value = rect.left-12.5; // 12.5 是popup宽度的一半的一半
  }

  if(brushSizeOpen.value==true){
      brush_sizes.value.style.transform = "translateY(20em)";
        brushSizeOpen.value = false;
    }else{
       brush_sizes.value.style.transform = "translateY(0px)";
        brushSizeOpen.value = true;
    }
}

const allSize = reactive([2,4,6,8,10])
var swidth = ref(15);
var sheight = ref(15);

const setBrushSize = function(value){
  cursorSize.value =value
  var index = allSize.indexOf(value);
  swidth.value = 15 + (index+1)*3;
  sheight.value = 15 + (index+1)*3;
  toggleBrush();
}

const circleSize = function(num){
  // console.log("circleSize param="+num);
  var index = allSize.indexOf(num);
  return 15 + (index+1)*3;
}



// watchEffect(() => {
//   console.log("in wathEffect()");
//   if (!brushToolRef.value) return;
//   const rect = brushToolRef.value.getBoundingClientRect();
//   popupTop.value = rect.bottom;
//   popupLeft.value = rect.left -12.5; // 12.5 是popup宽度的一半的一半
// });

const savePng = function(){
  if(Drew==true){
        let File_Name="draw";
        var jpegUrl = mycanvas.toDataURL("image/jpg");
    
        const link = document.createElement("a");
          document.body.appendChild(link);
    
          link.setAttribute("href",jpegUrl);
          link.setAttribute("download",File_Name);
          link.click();
          document.body.removeChild(link);
    }else{
        alert("Draw first !");
    }
}
</script>

<template>
    <div class="container">
            <div id="tray" class="tray">
                 <!-- 笔刷大小 -->
                <div ref="brushToolRef" class="brushDiv" @click="toggleBrush()">
                  <button class="brushIcon"  :style="{width:swidth+'px',height:sheight+'px'}"></button>
                </div>

                <!-- 橡皮 -->
                <div ref="eraseRef" @click="enableErase($event )" class="well"><font-awesome-icon icon="eraser" class="toolbtn" /></div>

                <!-- 颜色 -->
                <div v-for="(color,index) in colors" :key="index" class="well" @click="colorClick($event)" :style="{backgroundColor: color} "></div>
               
               <!-- 清除 -->
                <div @click="clearAll()" class="well"><font-awesome-icon icon="trash-alt" class="toolbtn" /></div>
                
                <!-- 保存 -->
                <div @click="savePng()" class="well"><font-awesome-icon icon="save" class="toolbtn" /></div>
            </div>


            <!-- 画板关闭按钮 -->
            <div class="rightTop"><button @click="props.toggleBoard()">close</button></div>


            <!-- 画布 -->
            <canvas ref="mycanvas" 
            @mousedown="mouseDown($event)" 
            @mouseup="mouseUp($event)"
            @mousemove="mouseMove($event)"
            id="wboard" class="wboard" height="768" width="1024"></canvas>


            <!-- popup 笔刷笔头系列 -->
            <div ref="brush_sizes" 
            :style="{ top: popupTop+'px',left: popupLeft+'px' }" 
            v-show="brushSizeOpen" 
            class="brush_sizes">
                      <button v-for="s in allSize" 
                      :id="s"
                       @click="setBrushSize(s)" 
                      :style="{width:circleSize(s)+'px' ,height: circleSize(s)+'px'}">
                    </button>
                      <!-- <button id="cancel_brush_palette" @click="toggleBrush()"><font-awesome-icon icon="close" class="toolbtn" /></button> -->
            </div>
    </div>
</template>

<style scoped>
* {
  box-sizing: border-box;
}
*:before,
*:after {
  box-sizing: border-box;
}
/* body {
  padding: 0;
  height: 100%;
  margin: 0;
  white-space: nowrap;
  background: #fff url("../assets/images/clouds.png") no-repeat center center fixed;
  background-size: cover;
  overflow: hidden;
} */
div.well {
  display: inline-block;
  width: 32px;
  height: 32px;
  border-radius: 16px;
  
}

.toolbtn{
    width: 100%;
    height: 100%;
    padding: 2px;

   
}
.well :hover, .brushIcon:hover{
  transform: translateY(-5px);
}

div.well.clicked:after {
  content: '';
  width: 48px;
  height: 48px;
  top: -8px;
  left: -8px;
  display: block;
  border-radius: 24px;
  position: relative;
  border: 4px solid #707070;
}
div.container {
    width: 1024px;
    height: 768px;
  
  margin: 20px auto;
  /* border:4px solid red; */
  /* position: relative; */
}
div.rightTop{
  position: absolute;
  top:0;
  right:0;
}
div.tray {
  position: absolute;
  text-align: center;
  left: 0;
  right: 0;
  top: 30px;
  width: 400px;
  margin: 0 auto;
  padding: 10px;
  display: grid;
  grid-auto-flow: column;
  /* border: 3px solid green   ; */
 
}
canvas.wboard {
  cursor: crosshair;
  width: 1024px;
  height: 768px;
  border: 3px dashed #707070;
  display: inline-block;
  /* position: absolute;
  left:0px;
  top:0px; */
  background:#fff url("../assets/images/p6.png") repeat;
}

/******************************************v 
 以下选择画笔粗细 
 ******************************************v*/
.beSelected{
  background: rgb(4, 187, 233);
  border: 1px solid rgb(4, 187, 233);
}
.brushDiv{
  /* border:1px solid red; */
  margin-top: 2px;
  display: flex;
  align-items: center;
}
.color_selector,.brush_sizes{
    position: absolute;
    top:30px;
    left:30px;
    /* bottom: 100px;
    right: 20px;*/
    
    padding: 5px;
    border-radius: 5px;
    transform: translateX(20em);
    transition-duration: 0.5s;
    box-shadow: 0.1px 4px 8px 2px rgba(0, 0, 0, 0.1);
}

/** 关闭按钮 */
#cancel_color_palette,#cancel_brush_palette{
    position: absolute;
    background: #fff;
    top: 0;
    left: 0;
    height: 20px;
    width: 20px;
    border-radius: 50%;
    transform: translate(-15px,-10px);
    box-shadow: 0.1px 4px 8px 2px rgba(0, 0, 0, 0.4);
}

/** 每个圆圈 */
.brush_sizes button ,.brushIcon{
    background: #fff;
    height: 15px;
    width: 15px;
    outline: none;
    border-radius: 50%;
    /* margin-left: 10px; */
    cursor: pointer;
    transition-duration: 0.2s;
    border: 1px solid rgba(0, 0, 0, 0.4);
    box-shadow: 0.1px 4px 8px 2px rgba(0, 0, 0, 0.1);
}

/** 所有圆圈外的div */
.brush_sizes{
    /* bottom: 5.5em; */
    height: 200px;
    width:50px;
    top:5.5em;
    left:10em;
    display: grid;
    grid-auto-columns: auto;
    /* grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));  */
    justify-content: center; /* 水平居中对齐 */
    grid-column-gap: 20px; /* 设置间隔为20像素 */
    align-items: center;
    justify-items:center; 
}

.brush_sizes button:hover{
    transform: translateY(-5px);
}


#cancel_brush_palette{
    border: none;
    opacity: 0.1;
  
}

</style>